//
//  ImageClip.m
//  GreenZone
//
//  Created by student on 15/6/23.
//  Copyright (c) 2015年 student. All rights reserved.
//

#import "ImageClip.h"

@implementation ImageClip

/**
 *  由图片名获得一张图片
 */
+(UIImage *)imageWithJpgName:(NSString *)name{
    NSString *path = [[NSBundle mainBundle]pathForResource:name ofType:@"jpg"];
    UIImage *image = [UIImage imageWithContentsOfFile:path];
    return image;
}
+(UIImage *)imageWithPngName:(NSString *)name{
    NSString *path = [[NSBundle mainBundle]pathForResource:name ofType:@"png"];
    UIImage *image = [UIImage imageWithContentsOfFile:path];
    return image;
}


/**
 *  由图片与矩形区域获得一张裁剪后的图片
 */
+(UIImage *)imageWithImage:(UIImage *)image clipByRect:(CGRect)rect{
    CGImageRef imageRef = CGImageCreateWithImageInRect(image.CGImage, rect);
    CGRect newRect = CGRectMake(0, 0, CGImageGetWidth(imageRef), CGImageGetHeight(imageRef));
    UIGraphicsBeginImageContext(newRect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextDrawImage(context, newRect, imageRef);
    UIImage *clipImage = [UIImage imageWithCGImage:imageRef];
    UIGraphicsEndImageContext();
    return clipImage;
}

/**
 *  通过指定宽度将图片裁剪为图片组
 */
+(NSArray *)imageArrWithImage:(UIImage *)image clipByWidth:(CGFloat)width{
    int rowNum = image.size.height/width;
    int colNum = image.size.width/width;
    NSMutableArray *imageArr = [[NSMutableArray alloc]init];
    for (int row = 0; row<rowNum; row++) {
        for (int col = 0; col<colNum; col++) {
            CGRect rect = CGRectMake(col*width, row*width, width, width);
            CGImageRef imageRef = CGImageCreateWithImageInRect(image.CGImage, rect);
            CGRect newRect = CGRectMake(0, 0, CGImageGetWidth(imageRef), CGImageGetHeight(imageRef));
            UIGraphicsBeginImageContext(newRect.size);
            CGContextRef context = UIGraphicsGetCurrentContext();
            CGContextDrawImage(context, newRect, imageRef);
            UIImage *clipImage = [UIImage imageWithCGImage:imageRef];
            UIGraphicsEndImageContext();
            [imageArr addObject:clipImage];
        }
    }
    return imageArr;
}


@end
